/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate.dao;

import hibernate.entity.Login;
import util.HibernateUtil;

/**
 *
 * @author NDH
 */
public class LoginDAO extends AbstractDAO {

    public Login readByEmail(String mail) {
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            query = session.createQuery("from Login where email = :mail");
            query.setString("mail", mail);
            return (Login) query.list().get(0);
        } catch (Exception ex) {
            return null;
        } finally {
            session.close();
        }
    }

    public Login login(String user, String pass) {
        session = HibernateUtil.getSessionFactory().openSession();
        try {
            query = session.createQuery("from Login where username = :user and password = :pass");
            query.setParameter("user", user);
            query.setParameter("pass", pass);
            return (Login) query.list().get(0);
        } catch (Exception e) {
            return null;
        }
    }
     public int create(Login lg) {
        try {
            session = HibernateUtil.getSessionFactory().getCurrentSession();
            tx = session.beginTransaction();
            query = session.createQuery("from Login where username = :username");
            query.setParameter("username", lg.getUserName());
            if (query.list().size() > 0) {
                return 0;
            }
            session.save(lg);
            tx.commit();
            return 1;
        } catch (Exception ex) {
            tx.rollback();
            return -1;
        } finally {
            session.flush();;
            session.close();
        }
    }

    public int update(Login lg) {
        try {
            
//            Session session = null;s
            session = HibernateUtil.getSessionFactory().openSession();
            lg = (Login) session.merge(lg);
            tx = session.beginTransaction();
            session.save(lg);
            tx.commit();
            return 1;
        } catch (Exception e) {
            tx.rollback();
            return -1;
        } finally {
        }
    }
}
